package action;

import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import entity.User;

/**
 * 处理用户登录的Action
 * 
 * 表单验证 需要 继承 ActionSupport类 并重写 validate() 方法
 * 
 */
@SuppressWarnings("serial")
public class LoginAction extends ActionSupport {

	/**
	 * 定义输入参数
	 */
	private User user;

	/**
	 * 定义字符串集合
	 */
	private List<String> strList;

	/**
	 * 定义对象集合
	 */
	private List<User> userList;

	/**
	 * 编写验证方法
	 */
	@Override
	public void validate() {
		if (user.getName().length() == 0) {
			addFieldError("uname", "用户名不能为空");
		}
		if (user.getPassword().length() == 0) {
			addFieldError("upassword", "密码不能为空");
		}
		// 验证不通过时 默认 返回 INPUT 在 struts.xml 对应的action中需要设置对应的reuslt跳转的页面
	}

	public String execute() throws Exception {

		if ("admin".equals(user.getName())
				&& "admin".equals(user.getPassword())) {
			// 成功

			// 使用解耦方式获取request, session, application
			// ActionContext actionContext = ActionContext.getContext();
			// Map<String, Object> requset = (Map<String, Object>) actionContext
			// .get("request");
			// Map<String, Object> session = actionContext.getSession();
			// Map<String, Object> application = actionContext.getApplication();
			// session.put("u", user);

			// 使用耦合方式获取request, session, application
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			HttpSession session = request.getSession();
			ServletContext application = session.getServletContext();
			ServletContext application2 = ServletActionContext
					.getServletContext();
			session.setAttribute("su", user);

			// 设置集合 用于在 loginSuccess测试 s:iterator 标签
			// 对 集合初始化
			strList =  Arrays.asList(new String[]{"aaa","bbb","ccc"});
			User user1 = new User(1, "小明1", "123", "废纸");
			User user2 = new User(2, "小明2", "123", "废纸");
			User user3 = new User(3, "小明3", "123", "废纸");
			User user4 = new User(4, "小明4", "123", "废纸");
			userList = Arrays.asList(new User[]{user1,user2,user3,user4});
			return "success";
		}
		return "fail";
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<String> getStrList() {
		return strList;
	}

	public void setStrList(List<String> strList) {
		this.strList = strList;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

}
